package com.zjuh.goodboy.claw;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zjuh.goodboy.claw.link.Link;
import com.zjuh.goodboy.config.Configuration;
import com.zjuh.goodboy.context.AppContext;
import com.zjuh.goodboy.context.DefaultAppContext;
import com.zjuh.goodboy.filter.DefaultFilterContext;
import com.zjuh.goodboy.filter.Filter;
import com.zjuh.goodboy.filter.FilterContext;
import com.zjuh.goodboy.parsers.ItemExpr;

public class Processor {
	
	private static final Logger log = LoggerFactory.getLogger(Processor.class);
	
	private AppContext appContext;
	
	public Processor(AppContext appContext) {
		super();
		this.appContext = appContext;
	}
	
	public Processor(Configuration configuration) {
		super();
		appContext = new DefaultAppContext();
		appContext.init(configuration);
	}

	public void process(Link link, ItemExpr itemExpr) {
		String url = link.getUrl();
		log.info("proccess url:" + url);
		Clawer clawer = (Clawer)appContext.getObject("clawer");
		ClawerResult clawerResult = clawer.claw(url);
		if (!clawerResult.isSuccess()) {
			onFail(link, clawerResult);
		} else {
			onSuccess(link, clawerResult, itemExpr);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void onSuccess(Link link, ClawerResult clawerResult, ItemExpr itemExpr) {
		FilterContext filterConext = new DefaultFilterContext();
		filterConext.setAttribute("itemExpr", itemExpr);
		for (Filter filter : (List<Filter>)appContext.getObjects("filters")) {
			filter.onFilter(link, clawerResult.getData(), filterConext);
		}
	}
	
	private void onFail(Link link, ClawerResult clawerResult) {
		log.error("fail: " + link + ", response code:" + clawerResult.getCode());
	}
	
}
